package com.wms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.bean.PageBean;
import com.wms.code.MyCodeFactory;
import com.wms.dto.PurchaseDto;
import com.wms.entity.Purchase2;
import com.wms.mapper.PurchaseDetailMapper2;
import com.wms.mapper.PurchaseMapper2;
import com.wms.service.PurchaseService2;
import com.wms.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class PurchaseServiceImpl2 implements PurchaseService2 {

    @Autowired
    PurchaseMapper2 purchaseMapper2;
    @Autowired
    PurchaseDetailMapper2 purchaseDetailMapper2;


    @Override
    public PageBean getAll(PurchaseDto purchaseDto) {
        PageHelper.startPage(purchaseDto.getPage(),purchaseDto.getPageSize());
        List<Map> list=purchaseMapper2.selectAll(purchaseDto);
        PageInfo info=new PageInfo(list);
        return new PageBean(purchaseDto.getPage(),purchaseDto.getPageSize(),info.getTotal(),list);
    }

    @Override
    public Purchase2 getById(int id) {
        return purchaseMapper2.selectById(id);
    }

    @Transactional
    @Override
    public int save(Purchase2 purchase2) {
        String maxPurchaseCode = purchaseMapper2.getMaxCode();
            //根据最大编码生成新的编码
            String newPurchaseCode= MyCodeFactory.createPurchaseCode(maxPurchaseCode);
            purchase2.setPurchaseCode(newPurchaseCode);

        int rs=purchaseMapper2.addPurchase(purchase2);
        Assert.isZero(rs,"保存采购单失败");
        if(null!=purchase2.getPurchaseDetail2s()&&purchase2.getPurchaseDetail2s().size()>0){
           int rs2=purchaseDetailMapper2.batchSavePurchaseDetail(purchase2.getId(), purchase2.getPurchaseDetail2s());
            Assert.isZero(rs2,"保存明细失败");
        }
        return rs;
    }
}
